'''
Created on Aug 28, 2013

@author: loski
'''
import os
import subprocess

class DiscSpaceManager(object):
    '''
    Class with operations to manage the disk space.
    '''

    def calculate_available_size(self, path):
        """
        Calculates the available space of the device in which the path is mounted.
        
        @param path: path to check
        @return: free disk space in KB
        """
        df = subprocess.Popen(['df', '-k', path], stdout=subprocess.PIPE)
        output = df.communicate()[0]
        i = 0
        for x in output.split('\n')[0].split():
            if x.lower() in ['available', 'free']:
                return float(output.split('\n')[1].split()[i])
            else:
                i += 1
                
    def calculate_folder_size(self, path):
        """
        Calculates the size of all the files (*.mp3 or *.wma in the path)
        @param param: path to check
        @return: size in KB
        """
        total_size = 0.0
        for x in os.listdir(path):
            if not x.startswith('.'):
                    subitem = os.path.join(path, x)
                    if os.path.isdir(subitem):
                        total_size += self.calculate_folder_size(subitem)
                    else:
                        if subitem[-4:].lower() in ['.mp3', '.wma']:
                            total_size += os.path.getsize(subitem)
        return total_size/1024